﻿using MedicalCare.Configuration;
using MedicalCare.EntityMappings.EntityMaps;
using StructureMap.Configuration.DSL;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;

namespace MedicalCare.IoCSetup
{
    public class MedicalNHibernateRegistry : Registry
    {
        public MedicalNHibernateRegistry()
        {
            NHibernate.Cfg.Environment.UseReflectionOptimizer = false;
            var mcConnStr = ConfigurationManagement.GetConnectionStringSettings("MedicalCare").ConnectionString;
            var fluentConfiguration = Fluently.Configure()
                .Database(
                    MsSqlConfiguration
                        .MsSql2008
                        .AdoNetBatchSize(50)
                        .ConnectionString(
                            c =>
                            c.Is(mcConnStr))
                        .Dialect<CustomFunctionsMsSql2005Dialect>()
                        .DefaultSchema("dbo")
                        .ShowSql())
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserMap>(t => t.Namespace.Equals("MedicalCare.EntityMappings.EntityMaps")));
            
            ISessionFactory sessionFactory = fluentConfiguration.BuildSessionFactory();

            For<FluentConfiguration>().Singleton().Use(fluentConfiguration).Named("MedicalCareFluentConfig");
            For<ISessionFactory>().Singleton().Use(sessionFactory).Named("MedicalCareSessionFactory");
            For<ISession>().HybridHttpOrThreadLocalScoped().Use(ctx => ctx.GetInstance<ISessionFactory>("MedicalCareSessionFactory").OpenSession()).Named("MedicalCareSession");
        }
    }
}